package com.housekeeping.housekeeping.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.housekeeping.housekeeping.serviceItem.utils.ResponseUtils;
import com.housekeeping.housekeeping.serviceItem.utils.StatUtil;
import com.housekeeping.housekeeping.user.entity.AccountVo;
import com.housekeeping.housekeeping.user.service.UserService;
import com.housekeeping.housekeeping.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录
 * @author tomyeung-李尐达
 */
@WebServlet("/User/Login")
public class UserLoginController extends HttpServlet {
    private UserService service=new UserServiceImpl();

    /**
     * 用户登录
     * @param req  account   登录账户号
     * @param req  password  登录密码
     * @response   成功返回状态码200
     *             并将部分账户信息存入session
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        String password=req.getParameter("password");
        //非空判断
        if (account==null||password==null){ResponseUtils.fail(resp, StatUtil.PARAMS_VALID); }
        else {
           try {
               AccountVo acc = service.login(account, password);
               //返回1，登录成功
               if (acc!=null){
                   //将账户信息加入session域
                   req.getSession().setAttribute("account", acc);
                   //返回成功响应
                   ResponseUtils.success(resp,StatUtil.SUCCESS);
               }
               //否则,登录失败，返回失败响应
               else {ResponseUtils.fail(resp,StatUtil.USER_ACCOUNT_ERR);}
           }catch (Exception e)
           {
               ResponseUtils.fail(resp,StatUtil.INTERNET_ERR);
               e.printStackTrace();
           }
        }
    }
}
